package com.ruoyi.service.achievements.impl;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.mapper.achievements.AcvTpMapper;
import com.ruoyi.service.achievements.AcvTpService;
import com.ruoyi.util.ExcelUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

@Service
public class AcvTpServiceImpl implements AcvTpService {

    private static String[] headArray = new String[]{"部门", "岗位", "考核指标", "指标描述/计算公式", "达成目标", "评分标准", "指标配分(满分100分)"};

    @Autowired
    AcvTpMapper acvTpMapper;

    @Override
    public List<Map<String, Object>> findTwoDept(Map map) {
        return acvTpMapper.findTwoDept(map);
    }

    @Override
    public List<Map<String, Object>> findThreeDept(Map map) {
        return acvTpMapper.findThreeDept(map);
    }

    @Override
        public List<Map<String, Object>> findJobByDeptId(Map map) {
            return acvTpMapper.findJobByDeptId(map);
    }

    @Override
    public AjaxResult importTemplateFile(MultipartFile file) {
        //验证模板
        AjaxResult ajaxResult = this.templateValidation(file, headArray);
        if (Integer.parseInt(ajaxResult.get("code").toString()) == 0) {
            //验证数据,主要验证数据库是否有对应的部门和岗位
            AjaxResult ajaxResult1 = this.dataValidation(file);
            if (Integer.parseInt(ajaxResult1.get("code").toString()) == 0) {
                //模板和数据验证完成后将所有模板数据改为旧版本
                acvTpMapper.updateTemplateData();
                //导入模板数据
                List<Map<String, Object>> list = (List) ajaxResult1.get("data");
                int count = acvTpMapper.insertTemplateData(list);
                if (count > 1) {
                    return new AjaxResult(AjaxResult.Type.SUCCESS, "导入成功");
                } else {
                    return new AjaxResult(AjaxResult.Type.ERROR, "未成功导入数据");
                }
            }
            return ajaxResult1;
        } else {
            return ajaxResult;
        }
    }

    //模板验证
    public AjaxResult templateValidation(MultipartFile file, String[] headArray) {
        Workbook workbook = ExcelUtils.getWorkBook(file);
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
        if (workbook != null) {
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                return new AjaxResult(AjaxResult.Type.ERROR, "未找到工作薄");
            }
            Row row = sheet.getRow(0);
            if (row == null) {
                //查找头部就是第0行,row为空代表第0行找不到
                return new AjaxResult(AjaxResult.Type.ERROR, "未找到头部,请确认模板是否正确");
            }
            for (int i = 0; i < 7; i++) {
                Cell cell = row.getCell(i);
                if (cell == null) {
                    //头部一共7列，cell为空说明缺少列
                    return new AjaxResult(AjaxResult.Type.ERROR, "请导入正确的模板");
                }
                String value = ExcelUtils.getCellValue(cell, evaluator);
                if (!value.equals(headArray[i])) {
                    //对比固定模板数组,汉字不匹配说明模板不准确
                    return new AjaxResult(AjaxResult.Type.ERROR, "未找到头部列:" + headArray[i] + ",请检查模板是否正确");
                }
            }
        }
        return new AjaxResult(AjaxResult.Type.SUCCESS, "模板正确");
    }

    //数据验证
    public AjaxResult dataValidation(MultipartFile file) {

        List<Map<String, Object>> excelData = ExcelUtils.getExcelData(file, new String[]{"deptName", "jobName", "assessmentIndex", "describe", "goal", "standard", "distribution"});
        //验证文件有没有数据
        if (excelData.size() == 0) {
            return new AjaxResult(AjaxResult.Type.ERROR, "文件没有数据");
        }

        String deptName = "";
        String jobName = "";
        for (Map map : excelData) {
            if (map.get("deptName") == null || map.get("jobName") == null) {
                //非空判断
                return new AjaxResult(AjaxResult.Type.ERROR, "部门或岗位不能为空");
            }

            if (deptName.equals(map.get("deptName").toString()) && jobName.equals(map.get("jobName").toString())) {
                continue;
            }
            //查找部门是否存在
            int existenceDept = acvTpMapper.findIsExistenceDept(map.get("deptName").toString());
            if (existenceDept > 0) {
                //查找该岗位下是否存在该部门
                int existenceJob = acvTpMapper.findIsExistenceJobByDept(map.get("deptName").toString(), map.get("jobName").toString());
                if (existenceJob > 0) {
                    //存在即跳出本次循环
                    deptName = map.get("deptName").toString();
                    jobName = map.get("jobName").toString();
                    continue;
                } else {
                    //不存在直接结束
                    return new AjaxResult(AjaxResult.Type.ERROR, map.get("deptName").toString() + "下不存在岗位:[" + map.get("jobName").toString() + "]");
                }
            } else {
                return new AjaxResult(AjaxResult.Type.ERROR, "系统找不到该部门[" + map.get("deptName").toString() + "]");
            }
        }
        return new AjaxResult(AjaxResult.Type.SUCCESS, "模板正确", excelData);
    }


    @Override
    public int uploadTemplateData(MultipartFile file, String jobId) {
        //将老数据状态设为旧版本
        acvTpMapper.updateTemplateDataByJobId(jobId);
        //上传
        List<Map<String, Object>> excelData = ExcelUtils.getExcelData(file, new String[]{"assessmentIndex", "describe", "goal", "standard", "distribution"});
        return acvTpMapper.insertTemplateDataByJobId(excelData, jobId);
    }

    @Override
    public AjaxResult downloadTemplateByJobId(String jobId) {
        List<Map<String, Object>> list = acvTpMapper.findAssessmentDataByJobId(jobId);
        try {
            HSSFWorkbook wb = new HSSFWorkbook();
            HSSFSheet sheet = wb.createSheet("考核项模板");
            //新增一行
            HSSFRow row = sheet.createRow(0);
            HSSFCellStyle txtStyle1 = wb.createCellStyle();
            HSSFFont txtFont = wb.createFont();
            txtFont.setFontName("宋体");
            txtFont.setFontHeightInPoints((short) 9);
            txtFont.setBold(true);
            txtStyle1.setFont(txtFont);
            txtStyle1.setWrapText(true);
            txtStyle1.setAlignment(HorizontalAlignment.CENTER);
            txtStyle1.setVerticalAlignment(VerticalAlignment.CENTER);
            txtStyle1.setBorderBottom(BorderStyle.THIN);
            txtStyle1.setBorderLeft(BorderStyle.THIN);
            txtStyle1.setBorderTop(BorderStyle.THIN);
            txtStyle1.setBorderRight(BorderStyle.THIN);
            row.createCell(0).setCellValue("考核指标");
            row.createCell(1).setCellValue("指标描述/计算公式");
            row.createCell(2).setCellValue("达成目标");
            row.createCell(3).setCellValue("评分标准");
            row.createCell(4).setCellValue("指标配分(满分100分)");
            row.setHeightInPoints(50);
            for (Cell cell : row) {
                cell.setCellStyle(txtStyle1);
            }

            HSSFCellStyle txtStyle = wb.createCellStyle();
            HSSFFont txtFont1 = wb.createFont();
            txtFont1.setFontName("宋体");
            txtFont1.setFontHeightInPoints((short) 9);
            txtStyle.setFont(txtFont1);
            txtStyle.setWrapText(true);
            txtStyle.setAlignment(HorizontalAlignment.CENTER);
            txtStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            txtStyle.setBorderBottom(BorderStyle.THIN);
            txtStyle.setBorderLeft(BorderStyle.THIN);
            txtStyle.setBorderTop(BorderStyle.THIN);
            txtStyle.setBorderRight(BorderStyle.THIN);

            for (int i = 0; i < list.size(); i++) {
                row = sheet.createRow(i);
                Map map = list.get(i);
                row.createCell(0).setCellValue(map.get("assessment_index").toString());
                row.createCell(1).setCellValue(map.get("describe").toString());
                row.createCell(2).setCellValue(map.get("goal").toString());
                row.createCell(3).setCellValue(map.get("standard").toString());
                row.createCell(4).setCellValue(map.get("distribution").toString());
                row.setHeightInPoints(40);
                for (Cell cell : row) {
                    cell.setCellStyle(txtStyle);
                }
            }

            sheet.setColumnWidth(0, 35 * 256);
            sheet.setColumnWidth(1, 42 * 256);
            sheet.setColumnWidth(2, 32 * 256);
            sheet.setColumnWidth(3, 40 * 256);
            sheet.setColumnWidth(4, 20 * 256);

            String filePath = Global.getDownloadPath() + "岗位考核项数据.xls";
            FileOutputStream fileOut = new FileOutputStream(filePath);
            wb.write(fileOut);
            fileOut.close();
            return AjaxResult.success(0);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("失败");
        }
    }

    @Override
    public List<Map<String, Object>> findTemplateDataByJobId(String jobId) {
        return acvTpMapper.findTemplateDataByJobId(jobId);
    }
}
